<template>
    <div>
        <!-- 按钮区域-- -------------------- -->
        <div class="button-container">
            <div>
                <el-button type="primary" plain :icon="Plus" @click="handleAdd"
                    v-hasPermi="['system:user:add']">新增</el-button>
                <!-- <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['system:user:edit']">修改</el-button> -->
                <el-button type="danger" plain :icon="Delete" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['system:user:remove']">删除</el-button>
                <!-- <el-button type="info" plain :icon="Upload" @click="handleImport"
               v-hasPermi="['system:user:import']">导入</el-button>
            <el-button type="warning" plain :icon="Download" @click="handleExport"
               v-hasPermi="['system:user:export']">导出</el-button> -->
            </div>
            <div>
                <el-tooltip effect="dark" content="刷新" placement="top">
                    <el-button circle :icon="Refresh" @click="refresh" />
                </el-tooltip>
            </div>
        </div>

        <!-- 表格区域-------------------  -----------------------      -->
        <div>
            <el-table :data="tableList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column label="IP" align="center" prop="ip" />
                <el-table-column label="数据库名称" align="center" prop="dbName" :show-overflow-tooltip="true" />
                <el-table-column prop="status" label="数据库类型" >
                    <template #default="scope">
                        <el-tag type="primary" disable-transitions v-if="scope.row.type === 0">
                            MySQL
                        </el-tag>
                        <el-tag type="danger" disable-transitions v-if="scope.row.type === 1">
                            SQLServer
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="用户名" align="center" prop="username" :show-overflow-tooltip="true" />
                <el-table-column label="密码" align="center" prop="password" />
                <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-tooltip effect="dark" content="修改" placement="top">
                            <el-button link type="primary" :icon="Edit" @click="handleUpdate(scope.row)"
                                v-hasPermi="['system:user:edit']"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="删除" placement="top">
                            <el-button link type="primary" :icon="Delete" @click="handleDelete(scope.row)"
                                v-hasPermi="['system:user:remove']"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="代码生成" placement="top">
                            <el-button link type="primary" :icon="Tools" @click="handleGenerator(scope.row)"
                                v-hasPermi="['system:user:resetPwd']"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 添加或修改用户配置对话框---------------------------------------------------- -->
        <el-dialog :title="title" v-model="dialogFormVisible" width="600px" append-to-body @close="onDialogFormCancel">
            <el-form :model="form" :rules="rules" ref="ruleFormRef" label-width="120px">
                <el-form-item label="IP" prop="ip">
                    <el-input v-model="form.ip" placeholder="请输入数据库ip" maxlength="30" />
                </el-form-item>
                <el-form-item label="数据库名称" prop="dbName">
                    <el-input v-model="form.dbName" placeholder="请输数据库名称" maxlength="50" />
                </el-form-item>

                <el-form-item label="数据库类型">
                    <el-select v-model="form.type" placeholder="请选择">
                        <el-option v-for="item in dbTypeOptions" :key="item.id" :label="item.type"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" placeholder="请输入用户名" maxlength="30" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" placeholder="请输入手机号码" maxlength="11" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="onDialogFormConfirm">确 定</el-button>
                    <el-button @click="onDialogFormCancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 代码生成对话框---------------------------------------------------- -->
        <el-dialog title="代码生成" v-model="dialogFormVisiblecode" width="850px" append-to-body :close-on-click-modal="false"
            @close="onDialogFormCancelcode">
            <el-form :model="formcode" :rules="rulecode" ref="ruleFormRefcode" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="IP" prop="ip">
                            <el-input v-model="formcode.ip" placeholder="请输入数据库ip" maxlength="30" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="数据库名称" prop="dbName">
                            <el-input v-model="formcode.dbName" placeholder="请输数据库名称" maxlength="50" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="formcode.username" placeholder="请输入用户名" maxlength="30" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="密码" prop="password">
                            <el-input v-model="formcode.password" placeholder="请输入手机号码" maxlength="11" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="数据库类型">
                            <el-select v-model="formcode.type" placeholder="请选择">
                                <el-option v-for="item in dbTypeOptions" :key="item.id" :label="item.type"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="表名" prop="tableName">
                            <el-input v-model="formcode.tableName" placeholder="" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="模块名" prop="moduleName">
                            <el-input v-model="formcode.moduleName" placeholder="例如： system" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="模块包路径">
                            <el-input v-model="formcode.parentPackageNameJava" placeholder="例如： com.kedasiyu.system" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                      <!-- <el-col :span="12">
                        <el-form-item label="模块xml路径" prop="parentPackageNameResource">
                            <el-input v-model="formcode.parentPackageNameResource" placeholder="com/kedasiyu/system , 为空时与java包相同" />
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="12">
                        <el-form-item label="作者名" prop="authorName">
                            <el-input v-model="formcode.authorName" placeholder="例如： " />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-row>
                <span>执行结果：</span>
                    <el-input v-model="generatorResult" type="textarea" />
            </el-row>
            
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="onDialogFormConfirmcode">确 定</el-button>
                    <el-button @click="onDialogFormCancelcode">取 消</el-button>
                </div>
            </template>
        </el-dialog>




    </div>
</template>

<script setup>
import { Search, Refresh, Plus, Delete, Edit, Tools, CircleCheck } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { getListService, addService, getById, editService, deleteService, generatorService } from '@/api/sys/generator'
import { ElMessage, ElMessageBox } from "element-plus"

// 操作按钮区域----------------------------------------------------------------
// 操作区显示隐藏控制
const toggleSearch = () => {
    // console.log("toggleSearch--------------search.valeue", searchShow.value)
    if (searchShow.value) {
        searchShow.value = false
        return
    }
    searchShow.value = true
}
// 刷新
const refresh = () => {
    getPageList()
}
// 添加
const handleAdd = () => {
    title.value = addTite
    isAdd.value = true
    dialogFormVisible.value = true
}
// 修改
const handleUpdate = async (row) => {
    title.value = updateTite
    isAdd.value = false
    let result = await getById(row.id)
    form.value = result.data
    dialogFormVisible.value = true

}
/** 删除按钮操作 */
const handleDelete = (row) => {
    const Ids = [row.id] || ids.value;
    ElMessageBox.confirm('确认要删除吗？', '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        // 删除
        let result = await deleteService(Ids)
        if (result.code == 0) {
            ElMessage.success(result.msg ? result.msg : '删除成功')
            getPageList()
        } else {
            ElMessage.error(result.msg ? result.msg : '删除失败')
        }
    })
        .catch(() => { })
}
const handleImport = () => {

}
const handleExport = () => {

}

// 分页----------------------------------------------------------
// 分页数据总条数
const PageDataTotal = ref(0)
// 分页插件，每页条数发生改变时
const handleSizeChange = (val) => {
    searchForm.value.pageSize = val
    getPageList()
}
// 分页插件， 当页码发生改变时
const handleCurrentChange = (val) => {
    searchForm.value.currentPage = val
    getPageList()
}

// 分页查询
const getPageList = async () => {
    try {
        const result = await getListService()
        tableList.value = result.data;
    } catch (err) { }
    //console.log("tableData:", tableData);
}
getPageList()


// 表格区域----------------------------------------------------------------
// 表格数据
const tableList = ref()
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
/** 选择条数  */
const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

// 代码生成
const handleGenerator = async (row) => {
    let result = await getById(row.id)
    formcode.value = result.data
    dialogFormVisiblecode.value = true;
}
// 权限分配
const handleAuthRole = (row) => {


}

/** 添加修改相关表单----------------------------------------- */
const sys_user_sex = [
    {
        label: "男",
        value: 0
    },
    {
        label: "女",
        value: 1
    }
]
// 角色下拉选择数据
const dbTypeOptions = ref([
    {
        id: 0,
        type: "MySQL"
    },
    {
        id: 1,
        type: "SQLServer"
    }
])
const form = ref({
    id: "",
    name: "",
    url: "",
    type: "",
    ifrun: "",
    description: "",
})
let addTite = "添加数据源"
let updateTite = "修改数据源"
const title = ref(addTite)
const isAdd = ref(true)
const dialogFormVisible = ref(false)

// 重置对话框表单
const restForm = () => {
    form.value = {}
    title.value = addTite
    isAdd.value = true
}

// 提交对话框表单按钮事件
const onDialogFormConfirm = async () => {
    //1.验证表单
    if (!ruleFormRef.value) return
    //2.提交表单
    await ruleFormRef.value.validate((valid) => {
        if (valid) {    // 校验成功
            confirm()
        }
    })
}
// 取消对话表单框按钮事件
const onDialogFormCancel = () => {
    //console.log("cancel......======================")
    dialogFormVisible.value = false
    restForm()
}

// 提交表单
const confirm = async () => {
    console.log("confirm-------")
    if (isAdd.value) {
        console.log("confirm-add------")
        // 添加
        try {   // 添加成功
            let result = await addService(form.value)
            ElMessage.success(result.message ? result.message : '添加成功')
            // 关闭弹窗，清空表单
            dialogFormVisible.value = false
            restForm()
            getPageList()
            console.log("result-------")
        } catch (error) { }
    } else {
        console.log("update=======")
        //修改
        try {   // 修改成功
            let result = await editService(form.value)
            ElMessage.success(result.msg ? result.msg : '修改成功')
            // 关闭弹窗，清空表单
            dialogFormVisible.value = false
            restForm()
            getPageList()
        } catch (error) { }
    }

}

/** 表单校验 */
const ruleFormRef = ref(null)   // 定义表单组件的引用
const rules = ref({
    username: [{ required: true, message: "不能为空", trigger: "blur" }],
    password: [{ required: true, message: "不能为空", trigger: "blur" }],
    type: [{ required: true, message: "不能为空", trigger: "blur" }],
    ip: [{ required: true, message: "不能为空", trigger: "blur" }],
    dbName: [{ required: true, message: "不能为空", trigger: "blur" }],
})


// 代码生成-------------------------------------------------------------------------
const formcode = ref({
})
const generatorResult = ref()
const dialogFormVisiblecode = ref(false)
const ruleFormRefcode = ref()   // 定义表单组件的引用
// 重置对话框表单
const restFormcode = () => {
    form.value = {}
    ruleFormRefcode.value.resetFields()
}

// 提交代码生成
const onDialogFormConfirmcode = async () => {
    //1.验证表单
    if (!ruleFormRefcode.value) return
    //2.提交表单
    await ruleFormRefcode.value.validate(async (valid) => {
        if (valid) {    // 校验成功
            try {
                const result = await generatorService(formcode.value)
                //console.log("result: " + result)
                generatorResult.value = result.message
            } catch (e) {
                //console.log(e)
                generatorResult.value = e.data.message
            }
           
        }
    })
}
// 取消对话表单框按钮事件
const onDialogFormCancelcode = () => {
    dialogFormVisiblecode.value = false
    restFormcode()
}
const rulecode = ref({
    username: [{ required: true, message: "不能为空", trigger: "blur" }],
    password: [{ required: true, message: "不能为空", trigger: "blur" }],
    type: [{ required: true, message: "不能为空", trigger: "blur" }],
    ip: [{ required: true, message: "不能为空", trigger: "blur" }],
    dbName: [{ required: true, message: "不能为空", trigger: "blur" }],
    tableName: [{ required: true, message: "不能为空", trigger: "blur" }],
    authorName: [{ required: true, message: "不能为空", trigger: "blur" }],
    moduleName: [{ required: true, message: "不能为空", trigger: "blur" }],
    // parentPackageNameResource: [{ required: true, message: "不能为空", trigger: "blur" }],
    arentPackageNameJava: [{ required: true, message: "不能为空", trigger: "blur" }],
})



</script>